import React, { useEffect, useState, useCallback } from 'react'
import { useEditor, EditorContent } from '@tiptap/react'
import StarterKit from '@tiptap/starter-kit'
import Underline from '@tiptap/extension-underline'
import TextAlign from '@tiptap/extension-text-align'
import { TextStyle } from '@tiptap/extension-text-style'
import { Color } from '@tiptap/extension-color'
import { Highlight } from '@tiptap/extension-highlight'
import { Link } from '@tiptap/extension-link'
import { Image } from '@tiptap/extension-image'
import { Table } from '@tiptap/extension-table'
import { TableRow } from '@tiptap/extension-table-row'
import { TableCell } from '@tiptap/extension-table-cell'
import { TableHeader } from '@tiptap/extension-table-header'
import { TaskList } from '@tiptap/extension-task-list'
import { TaskItem } from '@tiptap/extension-task-item'
import { MenuBar } from './MenuBar'
import { ContextMenu, createEditorContextMenuItems } from '../../ContextMenu'
import { SparkPromptModal } from '../../SparkPrompt'
import { message, Modal } from 'antd'
import './styles.css'

export interface TipTapEditorProps {
  /** HTML内容 */
  content: string
  /** 内容变更回调 */
  onChange: (html: string) => void
  /** 主题 */
  theme?: 'light' | 'dark'
  /** 是否只读 */
  readOnly?: boolean
  /** 保存回调 */
  onSave?: () => void
  /** 文档标题，用于导出文件名 */
  documentTitle?: string
}

/**
 * TipTap富文本编辑器核心组件
 * 基于ProseMirror，支持丰富的文本格式化功能
 */
export const TipTapEditor: React.FC<TipTapEditorProps> = ({
  content,
  onChange,
  theme = 'light',
  readOnly = false,
  onSave,
  documentTitle
}) => {
  // 右键菜单状态
  const [contextMenuVisible, setContextMenuVisible] = useState(false)
  const [contextMenuPosition, setContextMenuPosition] = useState({ x: 0, y: 0 })
  const [hasSelection, setHasSelection] = useState(false)

  // 星星之火弹窗状态
  const [sparkPromptVisible, setSparkPromptVisible] = useState(false)
  const [selectedTextForSpark, setSelectedTextForSpark] = useState('')

  const editor = useEditor({
    extensions: [
      StarterKit,
      Underline,
      TextAlign.configure({
        types: ['heading', 'paragraph']
      }),
      TextStyle,
      Color,
      Highlight.configure({
        multicolor: true
      }),
      Link.configure({
        openOnClick: false,
        HTMLAttributes: {
          target: '_blank',
          rel: 'noopener noreferrer'
        }
      }),
      Image.configure({
        HTMLAttributes: {
          class: 'editor-image'
        }
      }),
      Table.configure({
        resizable: true
      }),
      TableRow,
      TableCell,
      TableHeader,
      TaskList,
      TaskItem.configure({
        nested: true
      })
    ],
    content,
    editable: !readOnly,
    onUpdate: ({ editor }) => {
      const html = editor.getHTML()
      onChange(html)
    },
    editorProps: {
      attributes: {
        class: `tiptap-editor ${theme}`
      }
    }
  })

  // 当外部content变化时更新编辑器内容
  useEffect(() => {
    if (editor && content !== editor.getHTML()) {
      editor.commands.setContent(content)
    }
  }, [content, editor])

  // 当主题变化时更新编辑器类名
  useEffect(() => {
    if (editor) {
      const { view } = editor
      const currentClasses = view.dom.className.split(' ')
      const themeClasses = currentClasses.filter(cls => cls !== 'light' && cls !== 'dark')
      view.dom.className = [...themeClasses, theme].join(' ')
    }
  }, [theme, editor])

  // 当只读状态变化时更新
  useEffect(() => {
    if (editor) {
      editor.setEditable(!readOnly)
    }
  }, [readOnly, editor])

  // 处理右键菜单显示
  const handleContextMenu = useCallback((e: React.MouseEvent) => {
    e.preventDefault()

    if (!editor) return

    // 检查是否有选中的文本
    const { from, to } = editor.state.selection
    const selectedText = editor.state.doc.textBetween(from, to, ' ')
    setHasSelection(selectedText.trim().length > 0)

    // 设置菜单位置
    setContextMenuPosition({ x: e.clientX, y: e.clientY })
    setContextMenuVisible(true)
  }, [editor])

  // 关闭右键菜单
  const handleCloseContextMenu = useCallback(() => {
    setContextMenuVisible(false)
  }, [])

  // 复制功能
  const handleCopy = useCallback(() => {
    if (!editor) return

    const { from, to } = editor.state.selection
    const selectedText = editor.state.doc.textBetween(from, to, '\n')

    navigator.clipboard.writeText(selectedText).then(() => {
      message.success('已复制', 1)
    }).catch(() => {
      message.error('复制失败')
    })
  }, [editor])

  // 剪切功能
  const handleCut = useCallback(() => {
    if (!editor) return

    const { from, to } = editor.state.selection
    const selectedText = editor.state.doc.textBetween(from, to, '\n')

    navigator.clipboard.writeText(selectedText).then(() => {
      editor.commands.deleteSelection()
      message.success('已剪切', 1)
    }).catch(() => {
      message.error('剪切失败')
    })
  }, [editor])

  // 粘贴功能
  const handlePaste = useCallback(async () => {
    if (!editor) return

    try {
      const text = await navigator.clipboard.readText()
      editor.commands.insertContent(text)
      message.success('已粘贴', 1)
    } catch (err) {
      message.error('粘贴失败，请使用Ctrl+V或Cmd+V')
    }
  }, [editor])

  // 星星之火功能
  const handleSparkPrompt = useCallback(() => {
    if (!editor) return

    const { from, to } = editor.state.selection
    const selectedText = editor.state.doc.textBetween(from, to, '\n')

    if (!selectedText.trim()) {
      message.warning('请先选中文字')
      return
    }

    setSelectedTextForSpark(selectedText)
    setSparkPromptVisible(true)
  }, [editor])

  // 续写功能
  const handleContinueWriting = useCallback(() => {
    if (!editor) return

    const { from, to } = editor.state.selection
    const selectedText = editor.state.doc.textBetween(from, to, '\n')

    Modal.info({
      title: '续写 - 当前选中的文字',
      content: (
        <div style={{
          maxHeight: '400px',
          overflowY: 'auto',
          padding: '12px',
          backgroundColor: '#f5f5f5',
          borderRadius: '4px',
          whiteSpace: 'pre-wrap',
          wordBreak: 'break-word'
        }}>
          {selectedText}
        </div>
      ),
      width: 600,
      okText: '确定'
    })
  }, [editor])

  // 缩写功能
  const handleSummarize = useCallback(() => {
    if (!editor) return

    const { from, to } = editor.state.selection
    const selectedText = editor.state.doc.textBetween(from, to, '\n')

    Modal.info({
      title: '缩写 - 当前选中的文字',
      content: (
        <div style={{
          maxHeight: '400px',
          overflowY: 'auto',
          padding: '12px',
          backgroundColor: '#f5f5f5',
          borderRadius: '4px',
          whiteSpace: 'pre-wrap',
          wordBreak: 'break-word'
        }}>
          {selectedText}
        </div>
      ),
      width: 600,
      okText: '确定'
    })
  }, [editor])

  // 创建右键菜单项
  const contextMenuItems = createEditorContextMenuItems({
    hasSelection,
    onCopy: handleCopy,
    onCut: handleCut,
    onPaste: handlePaste,
    onSparkPrompt: handleSparkPrompt,
    onContinueWriting: handleContinueWriting,
    onSummarize: handleSummarize
  })

  if (!editor) {
    return null
  }

  return (
    <div className={`rich-text-editor-container ${theme}`}>
      {editor && <MenuBar editor={editor} onSave={onSave} documentTitle={documentTitle} />}
      <div onContextMenu={handleContextMenu}>
        <EditorContent editor={editor} />
      </div>

      {/* 右键上下文菜单 */}
      <ContextMenu
        visible={contextMenuVisible}
        position={contextMenuPosition}
        items={contextMenuItems}
        onClose={handleCloseContextMenu}
      />

      {/* 星星之火弹窗 */}
      <SparkPromptModal
        visible={sparkPromptVisible}
        selectedText={selectedTextForSpark}
        onClose={() => setSparkPromptVisible(false)}
      />
    </div>
  )
}

export default TipTapEditor
